package com.nexgo.payment.action.scan;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.BmpUtils;
import com.nexgo.payment.util.ZXingUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkNotNull;


/**
 * 扫码输入
 *
 * Created by wanghongyang on 2017/9/1.
 */
public class BccScanOrderPresenter  implements BccScanOrderContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(BccScanOrderPresenter.class.getSimpleName());

    private final BccScanOrderContract.View mView;
    private DataSource mRepository;
    private final Handler mHandler;
    private final TransData mTransData;
    private boolean mIsScanNext = false;
    private Bitmap mBitmap = null;
    private boolean isFirstTimes = true;
    public BccScanOrderPresenter(@NonNull BccScanOrderContract.View view, @NonNull DataSource dataSource, @NonNull TransData transData) {
        this.mView = checkNotNull(view);
        this.mRepository = checkNotNull(dataSource);
        mTransData = checkNotNull(transData);
        view.setPresenter(this);
        mHandler = new Handler(Looper.getMainLooper());
    }


    @Override
    public void start() {

        mBitmap = ZXingUtil.createBitmap(mTransData.getPayCodeNo());
        mLog.debug("mTransData.getPayCodeNo() {} ,{} ",mTransData.getPayCodeNo(),mBitmap == null );

        if(isFirstTimes) {
            postMainThread(() -> mView.showCountTime(SysConstant.TIME_OUT_60));
            postMainThread(() -> mView.showQrCode(mBitmap));
            isFirstTimes = false;
        }
    }

    @Override
    public void pause() {}

    @Override
    public void destroy() {}



    private void postMainThread(Runnable runnable) {
        if (mView.isActive()) {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                runnable.run();
            } else {
                mHandler.post(runnable);
            }
        }
    }

    @Override
    public Bitmap createQrdata(String url) {
        return BmpUtils.str2Bitmap(url);
    }

    @Override
    public void showOnScanNextAndRestart() {
        if (!mIsScanNext) return;
         postMainThread(() -> mView.showQrCode(mBitmap));
        mIsScanNext = true;
    }
}
